package com.etc.delivery.service.appoint.impl;

import com.etc.delivery.dao.appoint.IAppointmentDao;
import com.etc.delivery.dao.user.IUserDao;
import com.etc.delivery.entity.Address;
import com.etc.delivery.entity.Appointment;
import com.etc.delivery.entity.User;
import com.etc.delivery.entity.Waybill;
import com.etc.delivery.service.appoint.IAppointmentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class AppointmentServiceImpl implements IAppointmentService {

    @Resource
    private IAppointmentDao iAppointmentDao;
    @Resource
    private IUserDao iUserDao;

    @Override
    public boolean appoint(Appointment appoin) {
        int mail_cost = appoin.getMail_cost();
        String phone = appoin.getSender_phone();
        User user = iUserDao.queryUserPhone(phone);
        double balance = user.getBalance();
        int cost_i = appoin.getMail_cost();
        double cost = (double) cost_i;
        boolean flag = false;
        if (balance >= cost) {
            boolean flag2 = iUserDao.updateBalance(mail_cost, phone);
            boolean flag1 = iAppointmentDao.appoint(appoin);
            flag = flag1 && flag2;

        } else if (balance < cost) {
            flag = false;

        }

        return flag;
    }

    @Override
    public List<Appointment> showAllAppoint() {
        return iAppointmentDao.showAllAppoint();
    }

    @Override
    public List<Appointment> showAllAppointByPhone(String phone) {

        return iAppointmentDao.showAllAppointByPhone(phone);
    }

    @Override
    public PageInfo<Appointment> showAllAppointByPhonePage(String phone, int pageNum, int pageSize) {

        PageHelper.startPage(pageNum, pageSize);

        List<Appointment> alist = iAppointmentDao.showAllAppointByPhone(phone);
        PageInfo<Appointment> pageInfo = new PageInfo<>(alist);
        return pageInfo;
    }

    @Override
    public double queryMoneyByType(int typeId) {
        return iAppointmentDao.queryMoneyByType(typeId);
    }

    @Override
    public boolean add(List<Waybill> waybill) {
        return iAppointmentDao.add(waybill);
    }

    @Override
    public boolean deleteAppoin(int waybill_no) {
        Appointment appointment = iAppointmentDao.queryAppointByNo(waybill_no);
        int mail_cost = appointment.getMail_cost();
        String phone = appointment.getSender_phone();
        boolean flag = iUserDao.updateBalance1(mail_cost, phone);
        boolean flag1 = false;
        if (flag) {
            flag1 = iAppointmentDao.deleteAppoin(waybill_no);
        }

        return flag = flag && flag1;
    }

    @Override
    public List<Address> queryProvince() {
        return iAppointmentDao.queryProvince();
    }

    @Override
    public List<Address> queryCity(Integer id) {
        return iAppointmentDao.queryCity(id);
    }
}
